package ru.budget.mobile.ui.transactions

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.*
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.*
import org.koin.android.ext.koin.*
import org.koin.compose.KoinApplication
import org.koin.core.logger.Level
import ru.budget.mobile.R
import ru.budget.mobile.di.*
import ru.budget.mobile.ui.base.*
import ru.budget.mobile.ui.components.*
import ru.budget.mobile.ui.consumption.currentDatetime
import ru.budget.mobile.ui.entities.*
import ru.budget.mobile.ui.entities.states.*
import ru.budget.mobile.ui.theme.*

@Composable
@Preview(
    showBackground = true,
    device = "id:Xiaomi POCO M5s"
)
fun TransactionScreenPreview() {
    val context = LocalView.current.context.applicationContext
    KoinApplication(
        application = {
            androidLogger(Level.DEBUG)
            androidContext(context)
            modules(
                databaseModule,
                viewModelsModule,
                domainModule,
                dataModule
            )
        }
    ) {
        TransactionScreen(
            budgetState = BudgetState()
        )
    }
}

object State {
    val selectedIndexed = mutableStateOf(CategoryEnum.ALL)

    val currentTransaction = mutableStateOf(TransactionType.CONSUMPTION)
}

@Composable
fun TransactionScreen(budgetState: BudgetState) {
    Scaffold(
        topBar = {
            Column(
                content = {
                    ToolBar(
                        title = "Транзакции",
                        color = white
                    )
                    ChoiceBar()
                }
            )
        },
        content = {
            Column(
                content = {
                    ProductList(
                        list = if (State.currentTransaction.value == TransactionType.CONSUMPTION) {
                            State.selectedIndexed.value = CategoryEnum.ALL
                            budgetState.consumptionState.consumptionList.map { consumption ->
                                Transaction(
                                    title = consumption.title,
                                    type = consumption.type,
                                    category = consumption.category,
                                    sum = consumption.sum,
                                    datetime = consumption.datetime
                                )
                            }
                        } else {
                            State.selectedIndexed.value = CategoryEnum.ALL
                            budgetState.incomeState.incomeList.map { income ->
                                Transaction(
                                    id = income.id,
                                    category = CategoryEnum.INCOME,
                                    sum = income.sum,
                                    datetime = income.datetime
                                )
                            }
                        }
                    )
                },
                modifier = Modifier
                    .padding(it)
                    .fillMaxSize()
                    .background(white),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            )
        },
        containerColor = white
    )
}

@Composable
private fun ChoiceBar() {
    Row(
        content = {
            dropdownMenuButton()
            Spacer(
                modifier = Modifier
                    .height(24.dp)
                    .width(2.dp)
                    .background(
                        color = gray4,
                        shape = RoundedCornerShape(100.dp)
                    )
            )
            CategoryList()

        },
        modifier = Modifier
            .padding(
                start = 16.dp
            )
            .fillMaxWidth()
            .height(64.dp),
        horizontalArrangement = Arrangement.spacedBy(
            space = 16.dp,
            alignment = Alignment.Start
        ),
        verticalAlignment = Alignment.CenterVertically
    )
}

@Composable
private fun CategoryList() {

    LazyRow(
        content = {
            items(
                if (State.currentTransaction.value == TransactionType.CONSUMPTION) typeOfConsumptionList else typeOfIncomeList
            ) { item ->
                TypeOfConsumptionItem(
                    typeOfConsumption = item,
                    onClick = {
                        State.selectedIndexed.value = if (State.selectedIndexed.value == item.category) item.category else item.category
                    },
                    selected = State.selectedIndexed.value == item.category
                )
            }
        },
        horizontalArrangement = Arrangement.spacedBy(
            12.dp,
            alignment = Alignment.Start
        ),
        contentPadding = PaddingValues(
            end = 18.dp
        )
    )
}

private fun sortFirstByDatetime(list: List<Transaction>, item: Transaction): Boolean =
    list.first {
        it.datetime == item.datetime
    } == item

private fun totalAmount(list: List<Transaction>, item: Transaction): Double =
    list.filter {
        it.datetime == item.datetime
    }.sumOf {
        it.sum
    }

@Composable
private fun ProductList(list: List<Transaction>) {
    if (list.isNotEmpty()) {
        LazyColumn(
            content = {
                items(
                    items = list.filter {
                        if (State.selectedIndexed.value != CategoryEnum.ALL) {
                            State.selectedIndexed.value == it.category
                        } else true
                    }.sortedByDescending {
                        it.datetime.toString()
                    },
                    itemContent = { item ->
                        TransactionItemTemplate(
                            transaction = item,
                            visibleDate = sortFirstByDatetime(
                                list = list,
                                item = item
                            ),
                            sum = totalAmount(
                                list = list,
                                item = item
                            )
                        )
                    }
                )
            },
            modifier = Modifier
                .fillMaxSize(),
            verticalArrangement = Arrangement.spacedBy(0.dp)
        )
    } else {
        Text(
            text = "Здесь появятся Ваши транзакции.",
            style = TextStyle(
                fontSize = 20.sp,
                lineHeight = 23.sp,
                fontFamily = FontFamily(
                    Font(R.font.roboto)
                ),
                fontWeight = FontWeight.Bold,
                color = gray3
            )
        )
    }
}

@Composable
private fun TypeOfConsumptionItem(
    typeOfConsumption: TypeOfConsumption,
    onClick: () -> Unit,
    selected: Boolean
) {
    Card(
        modifier = Modifier
            .height(40.dp),
        content = {
            Row(
                modifier = Modifier
                    .padding(
                        start = 12.dp,
                        top = 8.dp,
                        end = 12.dp,
                        bottom = 8.dp
                    )
                    .fillMaxHeight(),
                horizontalArrangement = Arrangement.spacedBy(
                    space = 8.dp,
                    alignment = Alignment.CenterHorizontally
                ),
                verticalAlignment = Alignment.CenterVertically,
                content = {
                    if (typeOfConsumption.roundColor != Color(0)) {
                        Spacer(
                            modifier = Modifier
                                .height(16.dp)
                                .width(16.dp)
                                .background(
                                    color = typeOfConsumption.roundColor,
                                    shape = RoundedCornerShape(25.dp)
                                )
                        )
                    }
                    Text(
                        text = typeOfConsumption.title,
                        style = TextStyle(
                            fontSize = 16.sp,
                            lineHeight = 24.sp,
                            fontFamily = FontFamily(
                                Font(R.font.roboto)
                            ),
                            fontWeight = FontWeight.Medium,
                            color = if (selected) white else black
                        )
                    )
                }
            )
        },
        colors = CardColors(
            containerColor = if (selected) blue else gray5,
            contentColor = white,
            disabledContainerColor = if (selected) blue else gray5,
            disabledContentColor = white
        ),
        onClick = onClick
    )
}
